opening random access file

 The Open Statement for Random Access Files


 The "full blown" syntax for the Open statement was given in the previous topic on binary files.  The syntax for the Open statement, as it pertains to random files, is as follows:
If you only want to read from the random access file, use:


Open filename For Random Access Read As #filenumber Len = reclength


 and if you only want to write to the random access file, use:
 Open filename For Random Access Write As #filenumber Len = reclength


 and if you want to both read from and write to the random access file (for example, you want to access a particular record and then update one or more of its fields), use:
 Open filename For Random Access Read Write As #filenumber Len = reclength


 In the syntax formats above, reclength refers to the total length in bytes of all of the fields (variables) you define as part of a user-defined Type (UDT) structure. The variable that you base on the UDT serves as the storage facility, or record variable, into which a record from the random file is read, or from which a record to the random file is written.
For example, the sample program for this topic will use a random access version of the employee file we used in the topics on sequential files. The Type structure for the employee record will be defined as follows:

Private Type EmployeeRecord
EmpName As String * 20
DeptNbr As Integer
JobTitle As String * 25
HireDate As Date
HrlyRate As Single
End Type

The record variable based on this EmployeeRecord Type will be defined as:


Private Type mudtEmpRecord As EmployeeRecord


 Note that the String variables that make up this structure are defined as fixed-length strings. This is important for efficient access of the random file. Given that (in VB6 and lower), the size of an Integer is 2, the size of a Date is 8, and the size of a Single is 4, the total length of the structure above is 59 (20 + 2 + 25 + 8 + 4)
Thus, an Open statement for the random employee file could be written as:


 Open strRndEmpFileName For Random Access Read Write _
As #intRndEmpFileNbr Len = 59
 or, even easier and more flexible:
 Open strRndEmpFileName For Random Access Read Write _
As #intRndEmpFileNbr Len = Len(mudtEmpRecord)

 

In the syntax above, the Len function is used on the record variable, thus "letting the computer do the work" of figuring out the total length of the structure. And, using this method, if we add fields to or remove fields from the structure, we don't have to worry about recalculating the total length.

 

 

basic file handling by v. vanthana